﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Framework.Zhaogang.Utility.Core.IO
{
    /// <summary>
    /// 
    /// </summary>
    public class Compression
    {
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="logs"></param>
        /// <returns></returns>
        public static Stream GZipCompress(dynamic logs)
        {
            var json = JsonConvert.SerializeObject(logs);
            var bytes = Encoding.UTF8.GetBytes(json);
            var compressedBytes = default(byte[]);
            using (var memoryStream = new MemoryStream())
            {
                using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress))
                {
                    gZipStream.Write(bytes, 0, bytes.Length);
                    gZipStream.Close();
                    compressedBytes = memoryStream.ToArray();
                }
                memoryStream.Close();
            }
            return new MemoryStream(compressedBytes);
        }

        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="compressedMemoryStream"></param>
        /// <returns></returns>
        public static T GZipDecompress<T>(Stream compressedMemoryStream)
        {
            var logs = default(T);
            var ms = new MemoryStream();
            compressedMemoryStream.CopyTo(ms);
            var compressedBytes = ms.ToArray();
            var writeData = new byte[4096];
            var size = 0;
            var stringBuilder = new StringBuilder();
            using (var memoryStream = new MemoryStream(compressedBytes))
            {

                using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
                {
                    while ((size = gZipStream.Read(writeData, 0, writeData.Length)) > 0)
                    {
                        stringBuilder.Append(Encoding.UTF8.GetString(writeData, 0, size));
                    }
                    gZipStream.Close();
                    dynamic dynamicResult = JsonConvert.DeserializeObject(stringBuilder.ToString());
                    logs = dynamicResult.ToObject<T>();
                }
            }
            return logs;
        }
    }
}
